package com.quasar.hpatient.module.home_medicine_today;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.quasar.hpatient.R;
import com.quasar.hpatient.api.HttpClient;
import com.quasar.hpatient.api.HttpParams;
import com.quasar.hpatient.bean.home.HomeBean;
import com.quasar.hpatient.bean.home_inspection.CalendarBSBean;
import com.quasar.hpatient.bean.home_medicine.CalendarDoseBean;
import com.quasar.hpatient.bean.home_medicine.MedicineTodayBean;
import com.quasar.hpatient.bean.home_medicine_oral.MedicineOralItemBean;
import com.quasar.hpatient.dialog.CalendarDialog;
import com.quasar.hpatient.module.home.HomeView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import io.reactivex.Observable;
import lib.quasar.base.frame.BasePresenter;
import lib.quasar.base.frame.OnModelAcceptChangeListener;
import lib.quasar.context.BaseApp;
import lib.quasar.db.table.Medicine;
import lib.quasar.recycler.BaseCommonAdapter;
import lib.quasar.recycler.holder.RecyclerHolder;
import lib.quasar.recycler.manager.CrashLinearLayoutManager;
import lib.quasar.util.DimenUtil;
import okhttp3.RequestBody;

/**
 * description: 当日服药记录
 * created by kalu on 2018/5/10 8:43
 */
public class MedicineTodayPresenter implements BasePresenter {
    int warn_sign = 0;
    int status = 0;

    public TextView getHeadDateView() {
        return headDateView;
    }

    TextView  headDateView = null;

    private final LinkedList<MedicineTodayBean.ItemBean> mDatas = new LinkedList<>();
    public MedicineTodayBean.ItemBean getBean(int position){

        if (position<0 || position>=mDatas.size())
            return null;
        return mDatas.get(position);
    }


    public boolean isDoseAll(){
        for (MedicineTodayBean.ItemBean bean:mDatas) {
            if (bean.getStatus() == 0)
                return false;

        }
        return true;
    }

    void initList(MedicineTodayView view, RecyclerView recycler) {

        final BaseCommonAdapter<MedicineTodayBean.ItemBean> adapter = new BaseCommonAdapter<MedicineTodayBean.ItemBean>(mDatas, R.layout.activity_home_medicine_oral_child) {

            @Override
            protected void onNext(RecyclerHolder holder, final MedicineTodayBean.ItemBean model, final int position) {

                if (model.isMedicineNull()){
                    view.setText(holder, R.id.activity_home_medicine_oral_child_name, "药品");
                    view.setText(holder, R.id.activity_home_medicine_oral_child_number, "剂量");
                    view.setText(holder, R.id.activity_home_medicine_oral_child_unit,"规格");
                    view.setText(holder, R.id.activity_home_medicine_oral_child_time,"时间");
                    view.setText(holder, R.id.activity_home_medicine_oral_child_state,"状态");
                    view.setTextColor(holder, R.id.activity_home_medicine_oral_child_state, R.color.color_black);
                    return;
                }

                holder.setOnClickListener(R.id.activity_home_medicine_oral_child_state, v -> {
                    if (model.isMedicineOral()) {
                        view.toast(model.getMname() + ": 已经服用过了");
                    } else {

                        view.showHint(position,getDoseStatus(model));
                    }
                });
                view.setText(holder, R.id.activity_home_medicine_oral_child_name, model.getMname());
                view.setText(holder, R.id.activity_home_medicine_oral_child_number, model.getMedicineNumbers());
                view.setText(holder, R.id.activity_home_medicine_oral_child_unit, model.getDose_name());
                view.setText(holder, R.id.activity_home_medicine_oral_child_time, model.getMedicineTime());
                view.setText(holder, R.id.activity_home_medicine_oral_child_state, model.getMedicineInfo());
                view.setTextColor(holder, R.id.activity_home_medicine_oral_child_state, model.getMedicineColors());



            }
        };

        final View head = LayoutInflater.from(BaseApp.getContext()).inflate(R.layout.activity_home_today_medical_head, null);
        final RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DimenUtil.dp2px(50));
        params.topMargin = DimenUtil.dp2px(10);
        head.setLayoutParams(params);
        adapter.addHead(head);
        final TextView time = head.findViewById(R.id.home_medical_time);
        headDateView = time;

        view.setText(time, getDateLittle());
        time.setOnClickListener(v -> view.showCalendar());

        head.findViewById(R.id.home_medical_flush).setOnClickListener(v -> recordList(view, recycler, time.getText().toString()));
        head.findViewById(R.id.home_medical_all).setOnClickListener(v -> view.showWarning());


//        adapter.setNullView(BaseApp.getContext(), R.layout.activity_home_medicine_oral_head);
        final CrashLinearLayoutManager manager = new CrashLinearLayoutManager(BaseApp.getContext());
        view.setRecycler(recycler, adapter, manager);
    }

    void setTime(MedicineTodayView view, RecyclerView recycler, String time) {

        if (null == view || null == recycler || TextUtils.isEmpty(time)) return;

        final RecyclerView.Adapter adapter = recycler.getAdapter();
        if (null == adapter || !(adapter instanceof BaseCommonAdapter)) return;

        BaseCommonAdapter adapter1 = (BaseCommonAdapter) adapter;
        final LinearLayout head = adapter1.getHead();
        if (null == head) return;

        final TextView text = head.findViewById(R.id.activity_home_report_head_time);
        if (null == text) return;

        text.setText(time);
    }

    void recordList(MedicineTodayView view, RecyclerView recycler, String date) {

        if (null == view || null == recycler) return;

        if (mDatas.size() > 0) {
            mDatas.clear();
            view.refreshList(recycler);
        }

        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.PRESCRIPTION_DATE, TextUtils.isEmpty(date) ? getDate() : date);

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_5_4);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().medicineMessage(params);

        request(observable, new OnModelAcceptChangeListener<MedicineTodayBean>() {
            @Override
            public void modelSucc(MedicineTodayBean result) {

                if (null == result) {
                    modelFail();
                    return;
                }

                warn_sign = result.getWarn_sign();
                status = result.getStatus();

                final List<MedicineTodayBean.ItemBean> datas = result.getDatas();
                if (null == datas || datas.size() == 0) {
                    modelFail();
                    return;
                }

                for (MedicineTodayBean.ItemBean bean : datas) {
                        mDatas.addLast(bean);

                }

                MedicineTodayBean.ItemBean nullBean = new MedicineTodayBean.ItemBean();
                nullBean.setStatus(1);
                mDatas.addFirst(nullBean);

                view.refreshList(recycler);
                setTime(view,recycler,result.getPrescription_date());
            }

            @Override
            public void modelFail() {
//                RecyclerView.Adapter adapter = recycler.getAdapter();
//                if (adapter instanceof BaseCommonAdapter) {
//                    BaseCommonAdapter adapter1 = (BaseCommonAdapter) adapter;
//                    Context context = BaseApp.getContext();
//                    adapter1.setNullView(context, R.layout.layout_recycler_fail);
//                }
//                view.refreshList(recycler);
            }
        });
    }

    @Override
    public void recycler() {

    }


    final void editMedicineOral(final MedicineTodayView view, RecyclerView recycler, int position,int flag) {

        String prescriptionDate = getDate();
        final String usetime = getSecond();
        for (MedicineTodayBean.ItemBean temp : mDatas) {

            if (position == -1) {

                if (temp.isMedicineOral())continue;
                temp.setStatus(flag);
                temp.setReal_use_time(usetime);

            } else {

                final int i = mDatas.indexOf(temp);
                if (i == position) {
                    final String medicineTimes = getMedicineDate(temp.getUse_time());
                    temp.setReal_use_time(usetime);
                    temp.setStatus(flag);
                    if (1 == flag){

                        if (getDoseStatus(temp) == 0)
                            temp.setStatus(1);
                        else {
                            temp.setStatus(2);
                            warn_sign = 1;
                        }

                    }

                }
            }
        }

        if (isDoseAll())
            status = 1;

        LinkedList<MedicineTodayBean.ItemBean> temp = new LinkedList<MedicineTodayBean.ItemBean>();
        temp.addAll(mDatas);
        temp.removeFirst();
        final HashMap<String, Object> map = new HashMap<>();
        map.put(HttpParams.DOSE_DATE, prescriptionDate);
        map.put(HttpParams.JSON_CONTENT, temp);
        map.put(HttpParams.WARN_SIGN, warn_sign);
        map.put(HttpParams.STATUS, status);

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_5_5);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().uploadData(params);

        request(observable, new OnModelAcceptChangeListener<Object>() {
            @Override
            public void modelSucc(Object result) {


                view.toast("操作成功");


            }

            @Override
            public void modelFail() {

                if (position != -1) {
                    final MedicineTodayBean.ItemBean model = mDatas.get(position);
                    model.setStatus(0);
                    model.setReal_use_time("");
                }
                view.toast("操作失败");

            }

            @Override
            public void modelComplete() {
               // view.refreshList(recycler);

            }
        });

        view.refreshList(recycler);

    }

    int getDoseStatus(MedicineTodayBean.ItemBean bean){
        final String usetime = getSecond();
        final String medicineTimes = getMedicineDate(bean.getUse_time());
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            final Date date1 = sdf.parse(medicineTimes);
            final Date date2 = sdf.parse(usetime);
            if ((date2.getTime()-date1.getTime()) > 1800000)
                return 1;
            if ((date1.getTime()-date2.getTime()) > 1800000)
                return -1;

        }catch (Exception e) {
            return 0;
        }

        return 0;
    }


    final void schemelList(CalendarDialog dialog, String year, String month, String minDay, String maxDay) {

        final HashMap<String, Object> map = new HashMap<>();
        map.put(BEGIN_DATE, BaseApp.getResource().getString(R.string.date_calendar, year, month, minDay));
        map.put(END_DATE, BaseApp.getResource().getString(R.string.date_calendar, year, month, maxDay));
        //map.put(HttpParams.DAILY_ITEMNAME, HttpParams.JSON_BLOODSUGAR);

        final RequestBody params = createParams(map, HttpParams.DATA_TYPE_5_6);
        final Observable observable = HttpClient.getSingleHolder().getHttpService().schemeDoseList(params);

        request(observable, new OnModelAcceptChangeListener<List<CalendarDoseBean>>() {
            @Override
            public void modelSucc(List<CalendarDoseBean> list) {
                dialog.getCalendarView().setScheme(list);
            }
        });
    }


}
